package com.xiaolei.openokjoke.Activitys

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import com.bumptech.glide.Glide
import com.xiaolei.openokjoke.Base.BaseActivity
import com.xiaolei.openokjoke.Exts.gone
import com.xiaolei.openokjoke.Exts.show
import com.xiaolei.openokjoke.R
import kotlinx.android.synthetic.main.activity_image.*
import java.io.File
import kotlin.concurrent.thread

/**
 * 看图片的activity
 * Created by xiaolei on 2018/3/8.
 */
class ImageViewActivity : BaseActivity()
{
    private val url by lazy {
        intent.getStringExtra("url")
    }

    override fun onCreate(savedInstanceState: Bundle?)
    {
        setContentView(R.layout.activity_image)
        super.onCreate(savedInstanceState)
    }

    override fun initObj()
    {

    }

    override fun initView()
    {
        url?.let {
            click_download.show()
            Glide.with(this)
                    .load(R.drawable.icon_download)
                    .into(click_download)
        }
        url ?: let {
            click_download.gone()
        }
    }

    override fun initData()
    {

    }

    override fun setListener()
    {
        imageview.setOnClickListener {
            finish()
        }
        click_download.setOnClickListener {
            thread {
                val feature = Glide.with(this).asFile().load(url).submit()
                val file = feature.get()
                val dcimDir = File(Environment.getExternalStorageDirectory(), "DCIM")
                val saveDir = File(dcimDir, "OKJoke")
                val saveFile = File(saveDir, "${System.currentTimeMillis()}.gif")
                if (!saveDir.exists())
                {
                    saveDir.mkdirs()
                }
                if (!saveFile.exists())
                {
                    saveFile.createNewFile()
                }
                val fis = file.inputStream()
                val fos = saveFile.outputStream()

                val buff = ByteArray(1024)
                var len = fis.read(buff)
                while (len > 0)
                {
                    fos.write(buff, 0, len)
                    len = fis.read(buff)
                }
                fos.flush()
                fos.close()
                fis.close()
                runOnUiThread {
                    sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(saveFile)))
                    Toast("已保存至本地。")
                }
            }
        }
    }

    override fun loadData()
    {
        url ?: let {
            finish()
        }
        url?.let {
            Glide.with(this).load(url).into(imageview)
        }
    }

}